package httpService

import (
	"context"
	"encoding/json"
	"github.com/labstack/echo/v4"
	"github.com/smallnest/rpcx/client"
	"github.com/smallnest/rpcx/protocol"
	"os"
	"pm/config"
	process2 "pm/process"
	"pm/rpc"
	"strconv"
)

func ProcessLog(c echo.Context) error{
	processName := c.FormValue("process_name")
	logDate := c.FormValue("log_date")
	pageSize := c.FormValue("page_size")
	auto := c.FormValue("auto")
	logType := c.FormValue("log_type")
	//if processName == ""{
	//	return c.JSON(200, map[string]interface{}{
	//		"status": 1,
	//		"msg":"程序名称为空",
	//	})
	//}
	seek := c.FormValue("seek")
	seekNum,_ := strconv.ParseInt(seek, 10, 64)
	pageSizeNum ,_ := strconv.Atoi(pageSize)

	server := c.FormValue("server")
	if server != ""{
		d, _ := client.NewPeer2PeerDiscovery(server+":"+strconv.Itoa(rpc.Port), "")
		opt := client.DefaultOption
		opt.SerializeType = protocol.JSON
		var reply rpc.DataOutput
		params := map[string]interface{}{
			"file_name":         logDate,
			"seek":      seekNum,
			"page_size": pageSizeNum,
			"auto":auto,
			"log_type":logType,
			"process_name":processName,
		}
		paramsStr, _ := json.Marshal(params)
		xclient := client.NewXClient(rpc.ServerName, client.Failtry, client.RandomSelect, d, opt)
		err := xclient.Call(context.Background(), "process.log", string(paramsStr), &reply)
		if err != nil{
			return c.JSON(200, map[string]interface{}{
				"status": 1,
				"msg":err.Error(),
			})
		}else{
			if reply.Message != nil{
				return c.JSON(200, map[string]interface{}{
					"status": 1,
					"msg":reply.Message,
				})
			}
			var res map[string]interface{}
			json.Unmarshal([]byte(reply.Body.(string)), &res)
			res["status"] = 0
			return c.JSON(200, res)
		}
	}

	logFile := ""
	if logDate == "" && processName != ""{
		process := process2.NewProcess2().GetProcess(processName)
		if process == nil{
			return c.JSON(200, map[string]interface{}{
				"status": 0,
				"data":"",
				"seek":0,
				"total":0,
			})
		}
		if logType == process2.ErrorLogType{
			logFile = process.ErrorLog
		}else{
			logFile = process.Log
		}
	}else{
		logFile = config.ConfigData.Logs + string(os.PathSeparator)  + logDate
	}
	if logFile == ""{
		return c.JSON(200, map[string]interface{}{
			"status": 0,
			"data":"",
			"seek":0,
			"total":0,
		})
	}

	file, err1:= os.Open(logFile)
	if err1 != nil{
			return c.JSON(200, map[string]interface{}{
				"status": 0,
				"data":"",
				"seek":0,
				"total":0,
			})
	}
	defer file.Close()
	fileinfo, _ := file.Stat()

	fileSize := fileinfo.Size()

	if pageSizeNum <= 0{
		pageSizeNum = 1024 * 1024
	}

	if  fileSize < seekNum {
		seekNum = 0
	}

	data := make([]byte, pageSizeNum)
	//if auto != ""{
	//	file.Seek(seekNum, 0)
	//}else{
	//	_,err := file.Seek(seekNum, 2)
	//	if err != nil{
	//		fmt.Println(err.Error())
	//	}
	//}
	if seekNum < 0{
		var rseek int64
		if int64(pageSizeNum) < fileSize{
			rseek = -int64(pageSizeNum)
		}else{
			rseek = -fileSize
		}
		seekNum,_ = file.Seek(rseek, 2)
	}else{
		file.Seek(seekNum, 0)
	}
	realNum ,_ := file.Read( data)

	return c.JSON(200, map[string]interface{}{
		"status": 0,
		"data":string(data[:realNum]),
		"seek":seekNum + int64(realNum),
		"total":fileSize,
	})
}
